﻿using _RobotInspection.Attributes;
using _RobotInspection.DTO;
using _RobotInspection.Entities;
using _RobotInspection.Interfaces;
using _RobotInspection.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;

namespace _RobotInspection.Controllers
{
    /// <summary>
    /// 维修计划相关控制层
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    public class RepairPlanController : ControllerBase
    {
        private readonly IRepairPlanService _repairPlanService;
        private readonly IAttentionItemService _attentionItemService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repairPlanService"></param>
        /// <param name="attentionItemService"></param>
        public RepairPlanController(IRepairPlanService repairPlanService, IAttentionItemService attentionItemService)
        {
            _repairPlanService = repairPlanService;
            _attentionItemService = attentionItemService;
        }

        /// <summary>
        /// 分页查修维修计划
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<ApiResponse<RepairPlanPagedResultDto>>> GetRepairPlansPaged([FromQuery] RepairPlanPagedDto queryDto)
        {
            var result = await _repairPlanService.GetRepairPlansPagedAsync(queryDto);
            return new OkObjectResult(result);
        }


        /// <summary>
        /// 根据ID查询维修计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResponse<repair_plan>>> GetRepairPlanById([FromRoute] long id)
        {
            var result = await _repairPlanService.GetRepairPlanByIdAsync(id);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 创建维修计划（使用关注事项ID，不删除关注事项，不更新点检记录）
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        [ApiStatus(ApiStatusEnum.Testing)]
        [HttpPost]
        public async Task<ActionResult<ApiResponse<repair_plan>>> InsertRepairPlan([FromQuery] RepairPlanInsertDto queryDto)
        {
            // 根据关注事项查询点检记录ID
            var attentionItemResult = await _attentionItemService.GetAttentionItemByIdAsync(queryDto.AttentionItemId);
            if (attentionItemResult.Data == null)
            {
                return new OkObjectResult(attentionItemResult);
            }

            var repairPlanDto = new RepairPlanDto
            {
                RecordId = attentionItemResult.Data.record_id,
                UserId = queryDto.UserId,
                PlanName = queryDto.PlanName,
                BeginningTime = queryDto.BeginningTime,
                EndingTime = queryDto.EndingTime,
                Remark = queryDto.Remark,
            };
            var result = await _repairPlanService.InsertRepairPlanAsync(repairPlanDto);

            // 如果维修计划添加成功，删除关注事项
            if (result.Data != null)
            {
                //var deleteAttentionItem = await _attentionItemService.DeleteAttentionItemAsync(queryDto.AttentionItemId);
                //result.Message += $"，{deleteAttentionItem.Message}";
            }

            return new OkObjectResult(result);
        }

        /// <summary>
        /// 更新维修计划
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult<ApiResponse<repair_plan>>> UpdateRepairPlan([FromQuery] RepairPlanUpdateDto queryDto)
        {
            var result = await _repairPlanService.UpdateRepairPlanAsync(queryDto);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 删除维修计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResponse<repair_plan?>>> DeleteRepairPlan([FromRoute] long id)
        {
            var result = await _repairPlanService.DeleteRepairPlanAsyc(id);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 根据维修计划ID下载维修图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResponse<IActionResult>>> DownloadRepairPlanPictureById([FromRoute] long id)
        {
            try
            {
                var result = await _repairPlanService.GetRepairPlanByIdAsync(id);
                if (result.Data == null)
                {
                    return new OkObjectResult(result);
                }

                var picture_path = result.Data.picture_path;
                if (picture_path == null)
                {
                    return new OkObjectResult(ApiResponse<IActionResult>.Error($"维修图片下载失败：维修图片不存在", 400));
                }

                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", picture_path);
                new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string? contentType);
                contentType ??= "application/octet-stream";
                string fileName = Path.GetFileName(filePath);
                string encodedFileName = Uri.EscapeDataString(fileName);

                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                return File(fileStream, contentType, encodedFileName);
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<IActionResult>.Error($"维修图片下载失败：{ex.Message}", 500));
            }
        }
    }
}
